<?php

namespace App\middleware;

use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AdminAuth implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        if(in_array($request->path(), config('admin.ignore_urls', []))) return $next($request);
//        return $next($request);
        //需要验证token
//
        // 判断token可信性
        $auth_header = $request->header('Authorization');//获取token
        if(!$auth_header) return error('需要登录', [], 502);
        // 解析token
        $auth_token_arr = explode(' ', $auth_header);
        if (count($auth_token_arr) != 2 || $auth_token_arr[0] != 'Bearer' || empty($auth_token_arr[1])) return error('需要登录', [], 502);
        $token = $auth_token_arr[1];
        if (empty($token)) return error('需要登录', [], 502);
        // 解析token
        $playLoad = decode_auth_token($token);
        if ($playLoad['code'] !== 1){
            return error('需要登录', $playLoad['data'], 502);
        }
        $userInfo = $playLoad['data'];
        $request->loginUserId = $userInfo->id;
        return $next($request);
    }
}